package com.open.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;

import java.util.Base64;
import java.util.Date;

/**
 * @author page-view
 * <p>des</p>
 **/
@Slf4j
public class DESUtil {

    private static final SymmetricCrypto des;
    static {
        // sgEsnN6QWq8W7j5H01020304即为密钥明文长24位，
        // 不够则会随机补足24位
            des = new SymmetricCrypto(SymmetricAlgorithm.DES, "lposnN6QWasdowp291ksa01020304".getBytes());
    }

    public static String decrypt(String token){
        StringBuilder builder = new StringBuilder();
        char[] toCharArray = token.toCharArray();
        for (int i = 0; i < toCharArray.length; i++) {
            if (i % 2 == 0){
                builder.append(toCharArray[i]);
            }
        }
        return builder.toString();
    }
    /**
     * 解密头部信息 Accept-page-code
     * @param sign
     * @return
     */
    public static boolean decryptAcceptPageCode(String sign){
        try {
            sign = new String(Base64.getDecoder().decode(sign)).replaceAll("A","6").replaceAll("f","1");
            DateTime dateTime = DateUtil.date(new Date());
            int month = dateTime.month()+1;
            int day = dateTime.dayOfMonth();
            int dayValue = day * 9867;
            String firstMonth = sign.substring(0,Integer.toString(month).length());
            sign = sign.substring(3 + Integer.toString(month).length());
            sign = sign.substring(0,sign.length() - Integer.toString(dayValue).length());
            String newSign = sign.substring(0,sign.length() - 3);
            int dayLength = newSign.length() - Integer.toString(day).length();
            String vefMonth = newSign.substring(0, Integer.toString(month).length());
            String vefDay = newSign.substring(dayLength);
            String timeLength = newSign.substring( Integer.toString(month).length(),dayLength);
            timeLength = timeLength.substring(3);
            timeLength = decrypt(timeLength);
            String currentTime = (System.currentTimeMillis()/1000)+"000";
            return  Integer.parseInt(vefDay) == day &&
                    month == Integer.parseInt(vefMonth) &&
                    timeLength.length() == currentTime.length() &&
                    Integer.parseInt(firstMonth) == month &&
                    Integer.parseInt(firstMonth) == Integer.parseInt(vefMonth);
        }catch (Exception e){
            return false;
        }
    }
}
